package com.oj.interceptor;

import com.oj.entity.User;
import com.oj.service.PrivilegeService;
import com.oj.service.UserService;
import com.oj.util.AvatarUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Autowired
    private PrivilegeService privilegeService;

    //Controller逻辑执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            response.sendRedirect(request.getContextPath() + "/enter");
            return false;
        }

        String cookie_username = null;
        for (Cookie item : cookies) {
            if ("cookieOnlineJudgeUsername".equals(item.getName())) {
                cookie_username = item.getValue();
                break;
            }
        }

        String cookie_token = null;
        for (Cookie item : cookies) {
            if ("cookieOnlineJudgeToken".equals(item.getName())) {
                cookie_token = item.getValue();
                break;
            }
        }

        // 不存在cookie，则重定向到登录界面
        if (cookie_username == null || cookie_token == null) {
            response.sendRedirect(request.getContextPath() + "/enter");
            return false;
        }

        // TODO：这里应该在查一下账号与token的一致性
        User user = userService.query(cookie_username);
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/enter");
            return false;
        }

        request.getSession().setAttribute("session_username", user.getUsername());
        request.getSession().setAttribute("session_user_rate", user.getRate());
        request.getSession().setAttribute("session_user_admin", privilegeService.admin(user.getUsername()));

        String avatar_url = user.getAvatar();
        if (avatar_url == null || "".equals(avatar_url)) {
            avatar_url = AvatarUtil.avatarGenerate(user.getEmail());
        }
        user.setAvatar(avatar_url);
        userService.update(user);
        request.getSession().setAttribute("session_user_avatar_url", avatar_url);

        return true;
    }

    //Controller逻辑执行完毕但是视图解析器还未进行解析之前
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //System.out.println("LoginInterceptor postHandle....");
    }

    //Controller逻辑和视图解析器执行完毕
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //System.out.println("LoginInterceptor afterCompletion....");
    }
}
